import React, { Component } from 'react'
import {
  Text,
  View,
  StyleSheet,
  Platform,
  StatusBar,
  ScrollView,
  Dimensions,
  TextInput,
  TouchableOpacity,
  TouchableWithoutFeedback,
  DeviceEventEmitter,
} from 'react-native'
import Immutable from 'immutable'
import {
  Container,
  Header,
  Content,
  List,
  ListItem,
  Thumbnail,
  Body,
  Left,
  Right,
} from 'native-base'

import Icon from 'react-native-vector-icons/Ionicons'
import ItemList from '../component/ItemList'
import Button from '../component/Button'
import RootView from '../component/RootView'
import Base from './Base'
import {
  NavigationActions,
  px2dp,
  getBorderWidth,
  getAsyncStorage,
  imageServer,
} from '../utils'
import { toast } from '../utils/toast'
import * as orderService from '../services/order'
import * as cartService from '../services/cart'

const { width, height } = Dimensions.get('window')
const borderWidth = getBorderWidth()

class OrderConfirm extends Base {
  constructor(props) {
    super(props)
    this.state = {
      address: null,
      productList: Immutable.List(),
      orderPrice: {},
      couponText:'没有可使用的优惠券',
      couponAmount:0,
    }
  }
  static navigationOptions = {
    title: '填写订单',
    headerBackTitle: null,
    headerTitleStyle: {
      alignSelf: 'center',
    },
    headerStyle: {
      backgroundColor: 'white',
      borderBottomWidth: 0,
      shadowColor: 'transparent',
      elevation: 1,
    },
    headerRight: <View />,
  }

  loadData(data, addressId,couponId) {
    this.setState({ fetching: true })
    if (!addressId) {
      addressId = ''
    }
    if (!couponId) {
      couponId = 0
    }
    orderService
      .view({ data, addressId,couponId })
      .then(data => {
        
        let address = null
        if (data.address) {
          address = Immutable.fromJS(data.address)
        }
        if(data.coupon){
          
          let couponText=''
          if(data.coupon.condition>0){
            couponText='满'+data.coupon.condition+'减'+data.coupon.amount
          }else{
            couponText='立减'+data.coupon.amount
          }
          this.setState({
            fetching: false,
            address,
            couponText,
            noCoupon:data.noCoupon,
            couponId:data.couponId,
            couponAmount:data.coupon.amount,
            shipTime: data.shipTime,
            orderPrice: data.orderPrice,
            productList: Immutable.fromJS(data.productList),
          })
          return
        }
        this.setState({
          fetching: false,
          address,
          couponId:data.couponId,
          noCoupon:data.noCoupon,
          couponAmount:0,
          shipTime: data.shipTime,
          orderPrice: data.orderPrice,
          productList: Immutable.fromJS(data.productList),
        })
        
        
      })
      .catch(e => {
        this.setState({ fetching: false })
        toast(e.msg)
      })
  }
  async submitOrder() {
    await this.checkLogin()
    const { address, productList,couponId } = this.state
    if (address == null || !address.get('id')) {
      toast('请选择收货地址')
      return
    }
    this.setState({ fetching: true })

    let data = ''
    productList.map((item, i) => {
      if (i == 0) {
        data += `${item.get('productId')}#${item.get('num')}`
      } else {
        data += `|${item.get('productId')}#${item.get('num')}`
      }
    })
    const remark = this.refs.remark._lastNativeText || ''
    const params = {
      addressId: address.get('id'),
      couponId,
      remark,
      data,
    }
    orderService
      .create(params)
      .then(data => {
        // 清空购物车
        cartService
          .clearLocal()
          .then(d => {
            DeviceEventEmitter.emit('cart.reload')
            this.setState({ fetching: false })
            this.goto('Payment', { orderId: data.data })
          })
          .catch(e => {})
      })
      .catch(e => {
        this.setState({ fetching: false })
        toast(e.msg)
      })
  }
  renderAddress() {
    const { address } = this.state
    const { key } = this.props.navigation.state
    if (address) {
      const village = address.get('village')

      return (
        <ListItem
          style={{ marginLeft: 0, paddingLeft: 16, borderColor: '#e5e5e5' }}
          onPress={() => this.goto('Address', { key, selectable: 1 })}
        >
          <Body style={{ flex: 1 }}>
            <View style={{ flexDirection: 'row',alignItems:'center' }}>
              <Text style={{ marginRight: 10 }}>{address.get('name')}</Text>
              <Text>{address.get('phone')}</Text>
            </View>
            <View>
              <Text style={{ color: '#999', marginTop: 5 }}>{village}</Text>
            </View>
          </Body>
          <Right>
            <Icon
              name="ios-arrow-forward"
              size={24}
              style={{ color: '#999' }}
            />
          </Right>
        </ListItem>
      )
    }
    return (
      <ListItem
        style={{ marginLeft: 0, paddingLeft: 16, borderColor: '#e5e5e5' }}
        onPress={() => this.goto('Address', { key, selectable: 1 })}
      >
        <Body>
          <Text>选择收货地址</Text>
        </Body>
        <Right>
          <Icon name="ios-arrow-forward" size={24} style={{ color: '#999' }} />
        </Right>
      </ListItem>
    )
  }

  componentWillReceiveProps(nextProps) {
    if (
      nextProps.navigation.state.params &&
      (nextProps.navigation.state.params.addressId||nextProps.navigation.state.params.couponId)
    ) {
      const { data, addressId,couponId } = nextProps.navigation.state.params
      this.loadData(data, addressId,couponId)
    }
   
  }
  componentDidMount() {
    const { data } = this.props.navigation.state.params
    this.loadData(data)
  }

  render() {
    const { fetching, productList, shipTime,couponAmount,couponId,noCoupon } = this.state
    const { totalPrice, shipPrice, finalPrice } = this.state.orderPrice
    const { key } = this.props.navigation.state
    return (
      <RootView
        fetching={fetching}
        onModalClose={() => this.onModalClose()}
        style={styles.container}
      >
        <ScrollView style={{ marginTop: 10, flex: 1 }}>
          <List style={{ backgroundColor: 'white' }}>
            {this.renderAddress()}
            <ListItem
              style={{ marginLeft: 0, paddingLeft: 16, borderColor: '#e5e5e5' }}
            >
              <Body>
                <Text>送达时间</Text>
              </Body>
              <Right>
                <Text style={{ fontSize: 12, color: '#999' }}>
                  今日{shipTime}
                </Text>
              </Right>
            </ListItem>
          </List>
          
          <View style={styles.item}>
            <Text style={styles.label}>{'备注'}</Text>
            <View style={{ flex: 1 }}>
              <TextInput
                ref="remark"
                underlineColorAndroid="transparent"
                style={styles.textInput}
                placeholder="其他需求（如带一包红塔山）"
                placeholderTextColor="#888"
              />
            </View>
          </View>
          
          <Text style={{ padding: 16, backgroundColor: 'white', flex: 1 }}>
            商品信息
          </Text>
          <ItemList data={productList} />
          <TouchableOpacity activeOpacity={0.8} onPress={() => this.goto('Coupon',{ key,couponId,amount: totalPrice })}>
            <View style={styles.coupon}>
                <View style={{alignItems:'center'}}>
                  <Text>优惠券</Text>
                </View>

                <View style={{flex:1,alignItems:'center',justifyContent: 'flex-end',flexDirection: 'row' }}>
                    <Text style={{ color: '#999',marginRight:10 }}>
                      {noCoupon?'无优惠券':this.state.couponText}
                    </Text>
                    <Icon name="ios-arrow-forward" size={24} style={{ color: '#999',marginTop:2 }} />
                </View>
            </View>
          </TouchableOpacity>
          <List style={{ backgroundColor: 'white', marginTop: 10 }}>
            <ListItem style={{ borderColor: '#f0f0f0' }}>
              <Body>
                <Text>商品金额</Text>
              </Body>
              <Right>
                <Text style={{ color: '#e23f3c' }}>￥{totalPrice}</Text>
              </Right>
            </ListItem>
            <ListItem style={{ borderColor: '#f0f0f0' }}>
              <Body>
                <Text>配送费</Text>
              </Body>
              <Right>
                <Text style={{ color: '#e23f3c' }}>￥{shipPrice}</Text>
              </Right>
            </ListItem>
            <ListItem style={{ borderColor: '#f0f0f0' }}>
              <Body>
                <Text>优惠</Text>
              </Body>
              <Right>
                <Text style={{ color: '#e23f3c' }}>-￥{couponAmount}</Text>
              </Right>
            </ListItem>
            <ListItem style={{ borderColor: 'white' }}>
              <Body>
                <Text>合计</Text>
              </Body>
              <Right>
                <Text style={{ color: '#e23f3c' }}>￥{finalPrice}</Text>
              </Right>
            </ListItem>
          </List>
        </ScrollView>
        <View style={styles.cartView}>
          <View
            style={{
              flex: 1,
              justifyContent: 'center',
              paddingLeft: px2dp(15),
            }}
          >
            <Text style={{ color: '#444' }}>应付：￥{finalPrice}</Text>
          </View>
          <TouchableOpacity
            style={styles.buttonWrap}
            onPress={() => this.submitOrder()}
          >
            <Text style={[styles.button]}>{'提交订单'}</Text>
          </TouchableOpacity>
        </View>
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  item: {
    borderBottomWidth: borderWidth,
    backgroundColor: 'white',
    borderBottomColor: '#f0f0f0',
    paddingVertical: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  label: {
    minWidth: 45,
    color: '#222',
    paddingTop: 8,
    marginLeft: 16,
  },
  textInput: {
    flex: 1,
    paddingVertical: 0,
    height: 30,
    fontSize: 14,
    paddingHorizontal: 10,
  },
  cartView: {
    backgroundColor: '#fff',
    flexDirection: 'row',
    height: 46,
    elevation: 5, // for android
    shadowOffset: { width: 0, height: 0 },
    shadowColor: '#e5e5e5',
    shadowOpacity: 0.85,
    shadowRadius: 5,
  },

  buttonWrap: {
    flex: 1,
    height: 46,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#e23f3c',
  },
  button: {
    color: 'white',
  },
  coupon:{
    backgroundColor: 'white',
    alignItems:'center',
    flex:1,
    flexDirection: 'row',
    paddingRight:16,
    paddingLeft:16,
    paddingVertical:10,
    marginTop: 10
  }
})

export default OrderConfirm
